<template>
  <div v-if="visible">
    <el-dialog
      visible
      :title="title"
      append-to-body
      width="600px"
      @close="handleClose"
    >
      <el-input v-model="filterKey" clearable />

      <el-tree
        ref="tree"
        :data="data"
        node-key="id"
        show-checkbox
        :filter-node-method="handleFilter"
        :default-checked-keys="defaultValue"
        :default-expanded-keys="defaultValue"
      />

      <div slot="footer" class="footer">
        <el-button size="mini" @click="handleClose">
          取消
        </el-button>
        <el-button size="mini" type="primary" @click="handleOk">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'SelectTreeView',
  props: {
    visible: {
      type: Boolean,
      default: () => false
    },
    title: {
      type: String,
      default: () => '请选择'
    },
    data: {
      type: Array,
      default: () => []
    },
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {

      filterKey: ''

    }
  },
  computed: {
    defaultValue: function() {
      return (this.$props.value || []).map(e => {
        return typeof (e) === 'object' ? e.id : e
      })
    }
  },
  watch: {
    filterKey(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {

    handleClose() {
      this.$emit('close')
    },
    handleOk() {
      const data = this.$refs.tree.getCheckedNodes()
      const lastNodeList = data.filter(e => !e.children)
      this.$emit('submit', lastNodeList)
    },
    handleFilter(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }
  }
}
</script>

<style>

</style>
